package net.messagenet.mazor.infra.mbean;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import net.messagenet.mazor.DO.CustomerDO;
import net.messagenet.mazor.DO.DpaDO;
import net.messagenet.mazor.DO.DpaProductDO;
import net.messagenet.mazor.DO.PosDO;
import net.messagenet.mazor.DO.PosProductDO;
import net.messagenet.mazor.exception.MZRInternalServerException;
import net.messagenet.mazor.infra.cache.CacheManager;
import net.messagenet.mazor.infra.cache.UserCacheManager;
import net.messagenet.mazor.infra.engine.EngineInterface;
import net.messagenet.mazor.infra.excel.DpaExcelData;
import net.messagenet.mazor.infra.excel.ExcelManager;
import net.messagenet.mazor.infra.mail.MailManager;
import net.messagenet.mazor.infra.persistence.PersistenceManager;

import org.apache.log4j.Logger;
import org.jboss.ejb3.annotation.Management;
import org.jboss.ejb3.annotation.Service;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

@Service (objectName="MazorJMX:service=engine") 
@Management(EngineInterface.class)
public class EngineMbean implements EngineInterface{

	private Logger logger =  Logger.getLogger(this.getClass());
	private PersistenceManager persistenceManager ;
	private ExcelManager excelManager ;
	private MailManager mailManager ;
	private CacheManager cacheManager;

	
	/**
	 * This method is called by the container and is sets the entity manger
	 * to the mazor persistence manage
	 * 
	 * @param entityManager
	 */
	@PersistenceContext
	public void setEntityManager(final EntityManager entityManager){    
		this.persistenceManager.setEntityManager(entityManager);
	}
	
	
	public void create( )throws Exception {
		logger.info("*************************************");
		logger.info("*       STARTING MAZOR SYSTEM       *");
		logger.info("*************************************");
	
		logger.debug("building Engine mbean ");
		logger.debug("setting engine porperites form XML");
		XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("config.xml"));
		persistenceManager = (PersistenceManager)beanFactory.getBean("persistenceManager");
		excelManager =(ExcelManager)beanFactory.getBean("excelManager");
		mailManager = (MailManager)beanFactory.getBean("mailManager");
		cacheManager= (CacheManager)beanFactory.getBean("cacheManager");
		persistenceManager.setCacheManager(cacheManager);
		
		logger.debug("Engine mbean built");
		 
		logger.info("*************************************");
		logger.info("*       MAZOR SYSTEM STARTED        *");
		logger.info("*************************************");
	}


	@Override
	public void createDPARequest(DpaDO dpa) throws MZRInternalServerException {

		logger.debug("Creating new DPA");
		logger.debug("save DPA into DB");
		persistenceManager.saveDPARequest(dpa);
		logger.debug("creating excel file");
		String dpaRequestFilePath =excelManager.createDPARequestSheet(dpa,dpa.getFileName());
		logger.debug("sending file via mail");
		mailManager.sendDPASheetViaEmail(dpa.getEmail(),dpa.getCc(),dpaRequestFilePath);
	}
	
	@Override
	public void saveDPADraft(DpaDO dpa)
			throws MZRInternalServerException {
		logger.debug("Creating new DPA draft");
		logger.debug("save DPA into DB");
		persistenceManager.saveDPADraft(dpa);
		
	}

	
	public UserCacheManager getCacheManager (){
		if (!cacheManager.isDataFilled())
			persistenceManager.fillCache();
		return cacheManager;
	}


	@Override
	public void loadDPAAnswerSheet( String path) throws MZRInternalServerException {
		try {
			DpaExcelData data = excelManager.readDPADataFromFile(path);
			logger.debug("read data from excel dpa mzaor id is :"+data.dpaRequestId+" dpa number: "+data.dpaId+" exp date :" +data.ExperationDate);
			persistenceManager.updateDPARequest(data.dpaId,data.dpaRequestId,data.ExperationDate,data.approvedPrices);
			
			
		} catch (Exception e) {
			throw new MZRInternalServerException(e.getMessage(),e);
		}
		
	}


	@Override
	public Map<String,DpaDO> getAllApprovedDPAs() {
		return persistenceManager.getAllApprovedDPAs();
	}


	@Override
	public void createNewPOSRequest( PosDO posDo) throws MZRInternalServerException {
		logger.debug("Creating new DPA");
		logger.debug("save POS into DB");
		persistenceManager.savePOSrequest(posDo);
		logger.debug("update POS product quntity on dpa");
		persistenceManager.updateQuantityOnDPA(posDo.getPosProducts());
		logger.debug("creating excel file");
		String posRequestFilePath =excelManager.createPOSRequestSheet(posDo,posDo.getFileName());
		logger.debug("sending file via mail");
		mailManager.sendPOSSheetViaEmail(posDo.getEmail(),posDo.getCc(),posRequestFilePath);
		
	}


	@Override
	public void createOrEditCustomer( CustomerDO customer) {
		logger.debug("editing a customer");
		persistenceManager.createOrEditCustomer(customer);
		
	}


	@Override
	public List<DpaProductDO> getDPAReportedProducts(Date fromDate, Date toDate) {
		logger.debug("getting all reported products");
		return persistenceManager.getDPAReportedProducts(fromDate,toDate);
	}


	@Override
	public void updatePaidProducts( List<DpaProductDO> products) {
		logger.debug("updating products paid quantity");
		persistenceManager.updatePaidProducts(products);
		
	}


	@Override
	public List<DpaDO> getDPADrafts() {
		logger.debug("getting all drafts");
		return persistenceManager.getDPADrafts();
		 
	}


	@Override
	public void removeDPAProducts(List<DpaProductDO> removePrds) {
		logger.debug("removing products");
		persistenceManager.removeDPAProducts(removePrds);
		
	}


	@Override
	public List<PosDO> getPOSDrafts() {
		logger.debug("getting all pos drafts");
		return persistenceManager.getPOSDrafts();
	}


	@Override
	public void savePOSDraft( PosDO pos) {
		logger.debug("save POS into DB");
		persistenceManager.savePOSDraft(pos);
		
	}


	@Override
	public void removePOSProducts( List<PosProductDO> removePrds) {
		logger.debug("removing pos products");
		persistenceManager.removePOSProducts(removePrds);
		
	}

	@Override
	public Map<Integer, DpaDO> getAllNotClosedDPAs() {
		logger.debug("getting all not closed dpas");
		return persistenceManager.getAllNotClosedDPAs();
	}


	@Override
	public List<DpaDO> getClosedAndNotApprovedDPAs() {
		return persistenceManager.getClosedAndNotApprovedDPAs();
	}


	@Override
	public Map<Integer, DpaDO> getAllDPAs() {
		return persistenceManager.getAllDPAs();
	}

	
}

